import log from "./logger";
import {Player} from "./interfaces";
import {axios} from "../node-test";
import utils from "./utils";

class PlayerImpl implements Player {
    textArray: string[] = []
    lastMsg: string

    say(text: string, count: number = 1) {
        text = text.substr(0, 50);
        // 如果最后一个和这次的一样，不进行添加
        if (this.textArray[this.textArray.length - 1] === text) {
            return;
        }
        log.info(`add sayText:${text}`);
        this.lastMsg = text
        for (let i = 0; i < count; i++) {
            this.textArray.push(text);
        }
    }

    async sayText() {
        while (true) {
            const text = this.textArray.shift();
            if (text) {
                log.info("sayText:", text);
                axios.post("http://localhost:19999", text, {headers: {"Content-Type": "text/plain"}})
                    .catch((e) => {
                        log.error("sayText error")
                    });
                await utils.sleep(text.length * 300);
            }
            // 防止错误信息一直显示
            if (this.textArray.length <= 0) {
                this.lastMsg = "";
            }
            await utils.sleep(1000)
        }
    }

    init() {
        log.info("player init");
        this.sayText();
    }

    clear() {
        log.info("clear player");
        this.textArray = [];
        this.lastMsg = "";
    }
}

const player = new PlayerImpl();

export default player;
